package ynu.edu.online_course.service.Impl;

import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ynu.edu.online_course.entity.Banned;
import ynu.edu.online_course.entity.User;
import ynu.edu.online_course.mapper.UserMapper;
import ynu.edu.online_course.mapper.UserRoleMapper;
import ynu.edu.online_course.service.UserService;
import ynu.edu.online_course.mapper.BannedMapper;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BannedMapper bannedMapper;

    @Override
    public Long login(String telphone, String password) {
        User user = userMapper.findByTelephone(telphone);
        if (user != null && user.getPassword().equals(password)) {
            return user.getId();
        }
        return null;
    }

    @Override
    public Boolean register(User user) {
        if(getUserIdByTelephone(user.getTelephone()) == null) {
            userMapper.insertUser(user);
            return true;
        }
        else
            return false;
    }

    @Override
    public void updateUserInfo(User user) {
        userMapper.updateUser(user);
    }

    @Override
    public void deleteUser(Long userId) {
        userMapper.deleteUser(userId);
    }

    @Transactional
    @Override
    public void freezeUser(User user, User operatedBy) {

        userMapper.updateUserEnabled(user, false);

        Banned banned = new Banned();
        banned.setUser(user);
        banned.setOperatedBy(operatedBy);
        banned.setBannedAt(java.time.LocalDateTime.now());

        bannedMapper.insertBannedRecord(banned);
    }

    @Override
    public Long getUserIdByTelephone(String telephone) {
        if(userMapper.existsByTelephone(telephone)) {
            User user = userMapper.findByTelephone(telephone);
            return user.getId();
        }
        else return null;
    }
    @Override
    public void updatePassword(Long userId, String newPassword) {
        User user = userMapper.findById(userId);
        if (user != null) {
            // 判断新密码和旧密码是否相同
            if (user.getPassword().equals(newPassword)) {
                throw new RuntimeException("新旧密码相同");
            }

            // 更新密码
            user.setPassword(newPassword);
            userMapper.updateUser(user);
        } else {
            throw new RuntimeException("User not found");
        }
    }


    @Override
    public void updateTelephone(Long userId, String newTelephone) {
        if (userMapper.existsByTelephone(newTelephone)) {
            throw new RuntimeException("The telephone number is already registered");
        }
        User user = userMapper.findById(userId);
        if (user != null) {
            user.setTelephone(newTelephone);
            userMapper.updateUser(user);
        } else {
            throw new RuntimeException("User not found");
        }
    }

    @Override
    public void banUser(Banned banned) {
        // 检查用户是否存在
        User user = userMapper.findById(banned.getUser().getId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查操作者是否存在
        User operatedBy = userMapper.findById(banned.getOperatedBy().getId());
        if (operatedBy == null) {
            throw new RuntimeException("操作人不存在");
        }

        // 设置封禁时间和解封时间
        LocalDateTime bannedAt = LocalDateTime.now();
        LocalDateTime unbannedAt = bannedAt.plusMinutes(banned.getDurationInMinutes());
        banned.setBannedAt(bannedAt);
        banned.setUnbannedAt(unbannedAt);

        // 插入封禁记录
        bannedMapper.insertBannedRecord(banned);

        // 更新用户状态为禁用（假设用户表有active字段表示是否激活）
        user.setEnabled(false);
        userMapper.updateUser(user);
    }

    @Scheduled(fixedRate = 60000) // 每分钟检查一次
    public void unbanExpiredUsers() {
        LocalDateTime now = LocalDateTime.now();
        List<Banned> expiredBans = bannedMapper.findExpiredBans(now);
        for (Banned banned : expiredBans) {
            // 更新用户状态为解封
            User user = banned.getUser();
            user.setEnabled(true);
            userMapper.updateUser(user);

            // 删除封禁记录（可选，根据业务需求决定是否删除）
            bannedMapper.deleteById(banned.getId());
        }
    }
    UserRoleMapper userRoleMapper;
    @Override
    public boolean isAdmin(Long userId) {
        return userRoleMapper.isAdmin(userId);
    }

}

